using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data;
using System.Text;

public partial class Pages_RawStore : System.Web.UI.Page
{
    public static int addornegate = 1; // used to +/- of the saved item's quantity in ton/pcs default stock debit
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            TextBoxDate.Text = DateTime.Today.ToString();
            DropDownList1.SelectedIndex = 0;
            DropDownList1_SelectedIndexChanged(null, null);

            PopulateGrid();
        }

    }
    private void PopulateGrid()
    {

        #region populate and bind itemlist with grid
        DataSet ds = new DataSet();
        Common.Getdata(ds, "select ITYPE,ICODE,INAME,PRICE from stock", "Stk");

        Common.Getdata(ds, "select DESCRIPT,CODE from TYPE WHERE VARFIELD='ITYPE' and TYPE='RA' and CODE>0", "type");


        DataTable dtMemoBuffer = new DataTable();
        dtMemoBuffer.TableName = "dtMemoBuffer";
        dtMemoBuffer.Columns.Add("itype", typeof(float));
        dtMemoBuffer.Columns.Add("icode", typeof(float));
        dtMemoBuffer.Columns.Add("descript", typeof(string));
        dtMemoBuffer.Columns.Add("itypestring", typeof(string));
        dtMemoBuffer.Columns.Add("inamestring", typeof(string));
        dtMemoBuffer.Columns.Add("qty", typeof(decimal));
        dtMemoBuffer.Columns.Add("cost", typeof(decimal));
        dtMemoBuffer.Columns.Add("rowtotal", typeof(decimal));
        dtMemoBuffer.Columns.Add("acctype", typeof(int));
        dtMemoBuffer.Columns.Add("acccode", typeof(int));
        dtMemoBuffer.Columns.Add("acctypename", typeof(string));
        dtMemoBuffer.Columns.Add("accname", typeof(string));
        dtMemoBuffer.Columns.Add("ton", typeof(decimal));
       

        #endregion

        #region create data table for account input and bind it with grid
        
        DataTable dtMemoBuffer1 = new DataTable();
        dtMemoBuffer1.TableName = "dtMemoBuffer1";
        dtMemoBuffer1.Columns.Add("date", typeof(DateTime));
        dtMemoBuffer1.Columns.Add("nature", typeof(string));
        dtMemoBuffer1.Columns.Add("refn", typeof(float));
        dtMemoBuffer1.Columns.Add("amount", typeof(decimal));
        dtMemoBuffer1.Columns.Add("acccode", typeof(int));
        dtMemoBuffer1.Columns.Add("acctype", typeof(int));
        dtMemoBuffer1.Columns.Add("accname", typeof(string));
        dtMemoBuffer1.Columns.Add("acctypename", typeof(string));
        
        GridView2.DataSource = dtMemoBuffer1;
        GridView2.DataBind();

        

        #endregion

        if (Session["Raw Entry"] != null)
        {
            Session.Remove("Raw Entry");
        }
        Session.Add("Raw Entry", dtMemoBuffer);

        if (Session["Raw Account Entry"] != null)
        {
            Session.Remove("Raw Account Entry");
        }
        Session.Add("Raw Account Entry", dtMemoBuffer1);
    }
    protected void GridView3_SelectedIndexChanged(object sender, EventArgs e)
    {
        
        DataTable dtMemoBuffer = new DataTable();
        dtMemoBuffer = (DataTable)Session["Raw Entry"];
        if (GridView3.SelectedIndex > -1)
        {
            int i = GridView3.SelectedIndex;
            int cost = Convert.ToInt32(dtMemoBuffer.Rows[i]["cost"]);
            int qty = Convert.ToInt32(dtMemoBuffer.Rows[i]["qty"]);
            TextBoxqty.Text = cost.ToString();
            //TextBoxAmount.Text = qty.ToString();

        }

    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {

        DropDownList2.Items.Clear();
        DropDownList2.DataSource = null;

        if (DropDownList1.SelectedValue == "SRMC")
        {                        
            ListItem listIem = new ListItem();
            listIem.Text = "Cash Money receipt (CM)";
            listIem.Value = "CM";
            DropDownList2.Items.Add(listIem);

            ListItem listIem1 = new ListItem();
            listIem1.Text = "Bank Money receipt (BM)";
            listIem1.Value = "BM";
            DropDownList2.Items.Add(listIem1);

            ListItem listIem2 = new ListItem();
            listIem2.Text = "Journal Voucher (JV)";
            listIem2.Value = "JV";
            DropDownList2.Items.Add(listIem2);
            
           // BtnStkAccount.Text = DropDownList1.SelectedItem.Text;
            btnUpdateAcc.Text = "Account Debit";
            addornegate = -1;

            
        }
        else if (DropDownList1.SelectedValue == "SRMD")
        {
            ListItemCollection itemCollect = new ListItemCollection();

            ListItem listIem5 = new ListItem();
            listIem5.Text = "Cash Voucher (CD)";
            listIem5.Value = "CD";
            DropDownList2.Items.Add(listIem5);

            ListItem listIem6 = new ListItem();
            listIem6.Text = "Bank (BD)";
            listIem6.Value = "BD";
            DropDownList2.Items.Add(listIem6);

            ListItem listIem7 = new ListItem();
            listIem7.Text = "Journal Voucher (JV)";
            listIem7.Value = "JV";
            DropDownList2.Items.Add(listIem7);

         //   BtnStkAccount.Text = DropDownList1.SelectedItem.Text;
            btnUpdateAcc.Text = "Account Credit";
            addornegate = 1;
        }
        else if (DropDownList1.SelectedValue == "SDM")
        {

            addornegate = -1;
        }

         
        if ((DropDownList1.SelectedValue == "SRMC") ||(DropDownList1.SelectedValue == "SRMD"))
        {
            DropDownList2.SelectedIndex = 0;
            DropDownList2_SelectedIndexChanged(null, null);

            TextBoxRefSRM.Text = "SRM " + Common.GetRefn("SRM", Convert.ToDateTime(TextBoxDate.Text.ToString()).Year.ToString()).ToString();
        }

        if (DropDownList1.SelectedValue == "SDM")
        {
            TextBoxRefSRM.Text = "SDM " + Common.GetRefn("SDM", Convert.ToDateTime(TextBoxDate.Text.ToString()).Year.ToString()).ToString();
        }
        

        

        GridView1.DataSource = null;
        GridView1.DataBind();
        GridView3.DataSource = null;
        PopulateGrid();
    }
    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    protected void Button_account_amount_Click(object sender, EventArgs e)
    {
        try
        {

            if (!(Common.IsRightDecimalEntry(TextBox_accamount.Text)))
            {
                Label1.Text = "Incorrect decimal entry error 248";
                return;
            }

            decimal amount = Convert.ToDecimal(TextBox_accamount.Text);

            if (GridView2.SelectedIndex > -1)
            {
                DataTable dtAccBuffer = new DataTable();
                dtAccBuffer = (DataTable)Session["Raw Account Entry"];

                int i = GridView2.SelectedIndex;
                dtAccBuffer.Rows[i]["amount"] = amount;
                GridView2.DataSource = null;
                GridView2.DataSource = dtAccBuffer;
                GridView2.DataBind();
                GridView2.SelectedIndex = -1;

                if (Session["Raw Account Entry"] != null)
                {
                    Session.Remove("Raw Account Entry");
                }
                Session.Add("Raw Account Entry", dtAccBuffer);
                
            }

        }
        catch (Exception Ex)
        {

            Label1.Text = Ex.Message;
        }
    }
    protected void BtnUpdateAcc_Click(object sender, EventArgs e)
    {
        try
        {
            if (!(Common.IsRightDecimalEntry(TextBox_accamount.Text)))
            {
            Label1.Text="error 288"; return;
            }


            DataTable dtAccBuffer = new DataTable();
            dtAccBuffer = (DataTable)Session["Raw Account Entry"];


            #region If the account already exists in table do not add a new one again
            int k;
            int found = 0;

            for (k = 0; k < dtAccBuffer.Rows.Count; k++)  // find if the "sales of cisheet" account already exists
            {
                if (Convert.ToInt32(dtAccBuffer.Rows[k]["acctype"]) == Common.accTypeValue)
                    if (Convert.ToInt32(dtAccBuffer.Rows[k]["acccode"]) == Common.accCodeValue)
                    {
                        dtAccBuffer.Rows[k]["amount"] = Convert.ToInt32(TextBox_accamount.Text);
                        found = 1;
                    }

            }

            #endregion      
            
            if (found == 0)
            {
                DataRow dr = dtAccBuffer.NewRow();
                dr["acccode"] = Common.accCodeValue;
                dr["acctypename"] = Common.accTypeName;
                dr["accname"] = Common.accCodeName;
                dr["acctype"] = Common.accTypeValue;
                dr["amount"] = Convert.ToDecimal(TextBox_accamount.Text);

             dtAccBuffer.Rows.Add(dr);

            }


          
            GridView2.DataSource = null;
            GridView2.DataSource = dtAccBuffer;
            GridView2.DataBind();
            GridView2.SelectedIndex = -1;


            if (Session["Raw Account Entry"] != null)
            {
                Session.Remove("Raw Account Entry");
            }
            Session.Add("Raw Account Entry", dtAccBuffer);
        }
        catch (Exception Ex)
        {

            Label1.Text = Ex.Message;
        }
    }
    protected void GridView3_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        
        if (GridView3.SelectedIndex > -1)
        {
            DataTable dtMemoBuffer = new DataTable();
            dtMemoBuffer = (DataTable)Session["Raw Entry"];


            int i = GridView3.SelectedIndex;

            dtMemoBuffer.Rows.RemoveAt(i);
            dtMemoBuffer.AcceptChanges();

            GridView3.DataSource = null;
            GridView3.DataSource = dtMemoBuffer;
            GridView3.DataBind();

            GridView3.SelectedIndex = -1;

            if (Session["Raw Entry"] != null)
            {
                Session.Remove("Raw Entry");
            }
            Session.Add("Raw Entry", dtMemoBuffer); 

        }
    }
    protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
    {        
        //TextBoxRefNature.Text = DropDownList2.SelectedValue + " " + Common.GetRefn(DropDownList2.SelectedValue, DropDownListYear.SelectedValue.Trim()).ToString();
        TextBoxRefNature.Text = DropDownList2.SelectedValue.ToString() + " " + Common.GetRefn(DropDownList2.SelectedValue.ToString(), Convert.ToDateTime(TextBoxDate.Text.ToString()).Year.ToString()).ToString();
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {

        Label1.Text = "";
        #region Count how many accounts are there and load them to dtAccBuffer
        DataTable dtAccBuffer = new DataTable();
        dtAccBuffer = (DataTable)Session["Raw Account Entry"];
        decimal total_credit = 0;
        foreach (DataRow arow in dtAccBuffer.Rows)
        {
            total_credit = total_credit + Convert.ToDecimal(arow["amount"]);
        }
        int no_of_accounts = dtAccBuffer.Rows.Count;
        #endregion

        #region Bring all the filled up entries of dtMemoBuffer into another table dtBriefMemoBuffer
        DataTable dtMemoBuffer = new DataTable();
        dtMemoBuffer = (DataTable)Session["Raw Entry"];

        DataTable dtBriefMemoBuffer = dtMemoBuffer.Clone();

        //string filterExp = "qty > 0 || ton > 0";
        string filterExp = "";
        DataRow[] drarray;
        drarray = dtMemoBuffer.Select(filterExp);
        decimal total_ton = 0;
        decimal total_debit = 0;
        foreach (DataRow row in drarray)
        {
            dtBriefMemoBuffer.ImportRow(row);
            if (Convert.ToInt32(row["acctype"]) == 0 || Convert.ToInt32(row["acccode"]) == 0)  // means no account mentioned for this stock
            {
                Label1.Text = "error 405 : Debit account not mentioned";
                return;
            }
            total_ton = total_ton + Convert.ToDecimal(row["ton"]);
            total_debit = total_debit + Convert.ToDecimal(row["rowtotal"]);
        }
        int no_of_items = dtBriefMemoBuffer.Rows.Count;
        #endregion

        #region check if total_debit amount == total_credit amount
        if (total_debit != total_credit)
        {
            Label1.Text = "error 374 : total debit side is not equal to credit side";
            return;
        }
        #endregion


        #region connect to database and save dtBriefMemoBuffer to TRADE (Stock Account Debit/Credit) and item update in memo table

        string conString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
        //       string conString = @"Provider=SQLSql;Data Source=CSE-PC\SQLEXPRESS;User ID=sa;Initial Catalog=DB2011;Password=1234";
        SqlCommand myCommInsert = new SqlCommand();
        myCommInsert.Connection = new SqlConnection(conString);
        myCommInsert.Connection.Open();


        string vNature = "";
        int vRefn = Common.GetRefn(DropDownList2.SelectedValue.Trim(), Convert.ToDateTime(TextBoxDate.Text.ToString()).Year.ToString());
        int vRefnMemo = Common.GetRefn("SRM", Convert.ToDateTime(TextBoxDate.Text.ToString()).Year.ToString());

        int cacccode = 0;
        int cacctype = 0;
        int dacccode = 0;
        int dacctype = 0;
        decimal total_amount = 0;

        foreach (DataRow arow in dtBriefMemoBuffer.Rows)
        {
            // find out CREDITACC+CRACCTYPE AND DEBITACC+DEBACCTYPE Based on SRMC or SRMD

            if (DropDownList1.SelectedValue == "SRMC")
            {
                cacccode = Convert.ToInt16(arow["acccode"]);
                cacctype = Convert.ToInt16(arow["acctype"]);
                dacccode = no_of_accounts * (-1);
                dacctype = 0;
                vNature = "SRM";
            }
            else if (DropDownList1.SelectedValue == "SRMD")
            {
                dacccode = Convert.ToInt16(arow["acccode"]);
                dacctype = Convert.ToInt16(arow["acctype"]);
                cacccode = no_of_accounts * (-1);
                cacctype = 0;
                vNature = "SRM";
            }
            else if (DropDownList1.SelectedValue == "SDM")
            {
                dacccode = 0;
                dacctype = 0;
                cacccode = 0;
                cacctype = 0;
                vNature = "SDM";
            }
            total_amount = total_amount + Convert.ToDecimal(arow["rowtotal"]);
            if (DropDownList1.SelectedValue != "SDM")   // there is no account entry of stock for consumpotion 
            {

                string strQuery = "INSERT INTO [DB2011].[dbo].[TRADE]" +
                  " ([NATURE]" +
                  " ,[REFN]" +
                  " ,[IDOREQ]" +
                  " ,[DATE]" +
                  " ,[TIME]" +
                  " ,[CRACCTYPE]" +
                  " ,[CREDITACC]" +
                  " ,[DEBACCTYPE]" +
                  " ,[DEBITACC]" +
                    //" ,[RINSTRUM]" +
                  " ,[AMOUNT]" +
                    //" ,[BALDEBIT]" +
                    //" ,[BALCREDIT]" +
                  " ,[EXPLAIN]" +
                    //" ,[DELIVERYC]" +
                    //" ,[DEBEXP]" +
                    //" ,[CREDEXP]" +
                  " ,[TOTALTON])" +
            " VALUES (" +
                  "'" + DropDownList2.SelectedValue + "'" +
                  ",'" + vRefn + "'" +
                  "," + "null" +
                  ",'" + TextBoxDate.Text.Trim() + "'" +
                  ",'" + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + "'" +
                  ",'" + cacctype + "'" +
                  ",'" + cacccode + "'" +
                  ",'" + dacctype + "'" +
                  ",'" + dacccode + "'" +
                    //"," +
                  ",'" + Convert.ToDouble(arow["rowtotal"]) + "'" +
                    //"," +
                    //"," +
                  ",'" + TextBox_explain.Text.ToString() + "'" +
                    //"," +
                    //"," +
                    //"," +
                  ",'" + addornegate * Convert.ToDouble(arow["ton"]) + "')";
                myCommInsert.CommandText = strQuery;
                myCommInsert.ExecuteNonQuery();
            }
            string strQuery2 = "INSERT INTO [DB2011].[dbo].[MEMO]" +
                    "([DATE]" +
                    ",[NATURE]" +
                    ",[REFN]" +
                    ",[ICODE]" +
                    ",[QTY]" +
                    ",[ISSERIAL]" +
                    ",[COST]" +
                    ",[ITYPE]" +
                    ",[W_TON]" +
                    ",[DESCRIPT])" +
                    "VALUES" +
                    "('" + TextBoxDate.Text.Trim() + "'" +
                    ",'" + vNature + "'" +
                    ",'" + vRefnMemo + "'" +
                    ",'" + arow["icode"] + "'" +
                    ",'" + addornegate * Convert.ToDouble(arow["qty"]) + "'" +
                    "," + "null" +
                    ",'" + arow["cost"] + "'" +
                    ",'" + arow["itype"] + "'" +
                    ",'" + addornegate * Convert.ToDouble(arow["ton"]) + "'" +
                    "," + "null" + ")";
            myCommInsert.CommandText = strQuery2;
            myCommInsert.ExecuteNonQuery();


        }
        // put one entry of SRM/SDM into trade table
        string strQuery3 = "INSERT INTO [DB2011].[dbo].[TRADE]" +
    " ([NATURE]" +
    " ,[REFN]" +
    " ,[DATE]" +
    " ,[TIME]" +
    " ,[AMOUNT]" +
    " ,[TOTALTON])" +
    " VALUES (" +
     "'" + vNature + "'" +
     ",'" + vRefnMemo + "'" +
     ",'" + TextBoxDate.Text.Trim() + "'" +
     ",'" + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + "'" +
     ",'" + total_amount + "'" +
     ",'" + addornegate * total_ton + "')";
        myCommInsert.CommandText = strQuery3;
        myCommInsert.ExecuteNonQuery();

        // myCommInsert.Connection.Close();
        #endregion


        #region connect to database and save dtAccBuffer into Trade.dbf (Accounts Debit/Credit)


        if (DropDownList1.SelectedValue != "SDM")   // no account entry for SDM=consumption
        {
            foreach (DataRow accrow in dtAccBuffer.Rows)
            {

                if (DropDownList1.SelectedValue == "SRMC")
                {
                    dacccode = Convert.ToInt16(accrow["acccode"]);
                    dacctype = Convert.ToInt16(accrow["acctype"]);
                    cacccode = no_of_items * (-1);
                    cacctype = 0;

                }
                else if (DropDownList1.SelectedValue == "SRMD")
                {
                    cacccode = Convert.ToInt16(accrow["acccode"]);
                    cacctype = Convert.ToInt16(accrow["acctype"]);
                    dacccode = no_of_items * (-1);
                    dacctype = 0;


                }

                string strQuery = "INSERT INTO [DB2011].[dbo].[TRADE]" +
                    " ([NATURE]" +
                    " ,[REFN]" +
                    " ,[IDOREQ]" +
                    " ,[DATE]" +
                    " ,[TIME]" +
                    " ,[CRACCTYPE]" +
                    " ,[CREDITACC]" +
                    " ,[DEBACCTYPE]" +
                    " ,[DEBITACC]" +
                    " ,[AMOUNT]" +
                    " ,[TOTALTON])" +
              " VALUES (" +
                    "'" + DropDownList2.SelectedValue + "'" +
                     ",'" + vRefn + "'" +
                    "," + "null" +
                    ",'" + TextBoxDate.Text.Trim() + "'" +
                 ",'" + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + "'" +
               ",'" + cacctype + "'" +
               ",'" + cacccode + "'" +
               ",'" + dacctype + "'" +
               ",'" + dacccode + "'" +
               ",'" + Convert.ToDouble(accrow["amount"]) + "'" +
               "," + "null" + ")";
                myCommInsert.CommandText = strQuery;
                myCommInsert.ExecuteNonQuery();

            }
        }
        myCommInsert.Connection.Close();
        btnSave.Enabled = false;
        Label1.Text = "saved successfully";
        #endregion


    }


    protected void Button_PutItem_Click(object sender, EventArgs e)
    {

        Label1.Text = "";
        // check whether all entries are ok
        if (string.IsNullOrEmpty(Common.stkCodeName)) { Label1.Text = "error1"; return; }
        if (string.IsNullOrEmpty(TextBoxAmount.Text)) { Label1.Text = "error589"; return; }
        if (!Common.IsRightDecimalEntry(TextBoxAmount.Text)) { Label1.Text = "error590"; return; }
        if (Common.stkCodeValue < 1) { Label1.Text = "error2"; return; }
        
        if (!string.IsNullOrEmpty(TextBoxAmountNew.Text))
            if (!Common.IsRightIntegerEntry(TextBoxAmountNew.Text)) { Label1.Text = "error4"; return; }


        DataTable dtMemoBuffer = new DataTable();
        dtMemoBuffer = (DataTable)Session["Raw Entry"];

        //find if the selected entry is already in the table, if it is there update the price
        int k;
        int found = 0;
        decimal weight = 0;
        decimal pcs = 0;
        decimal unit_cost = 0;
        decimal total_cost = 0;

        for (k = 0; k < dtMemoBuffer.Rows.Count; k++)  // find if the selected item already exists
        {
            if (Convert.ToInt32(dtMemoBuffer.Rows[k]["itype"]) == Common.stkTypeValue)
                if (Convert.ToInt32(dtMemoBuffer.Rows[k]["icode"]) == Common.stkCodeValue)
                {
                    if (!(string.IsNullOrEmpty(TextBoxqty.Text)))
                    {
                        dtMemoBuffer.Rows[k]["qty"] = Convert.ToDecimal(TextBoxqty.Text);
                        weight = Convert.ToDecimal(TextBoxqty.Text);
                        dtMemoBuffer.Rows[k]["ton"] = 0;
                        

                    }
                    if (!(string.IsNullOrEmpty(TextBoxton.Text)))
                    {
                        dtMemoBuffer.Rows[k]["qty"] = 0;
                        weight = Convert.ToDecimal(TextBoxton.Text);
                        dtMemoBuffer.Rows[k]["ton"] = Convert.ToDecimal(TextBoxton.Text);
                    }
                    dtMemoBuffer.Rows[k]["rowtotal"] = Convert.ToDecimal(TextBoxAmount.Text);
                    dtMemoBuffer.Rows[k]["cost"] = Convert.ToDecimal(TextBoxAmount.Text) / weight;
                    //if (string.IsNullOrEmpty(TextBoxAmountNew.Text))
                    //{
                    //    dtMemoBuffer.Rows[k]["rowtotal"] = Convert.ToDecimal(TextBoxAmount.Text);
                    //    dtMemoBuffer.Rows[k]["cost"] = Convert.ToDecimal(TextBoxAmount.Text)/weight;
                    //}
                    //else
                    //{
                    //    dtMemoBuffer.Rows[k]["rowtotal"] = Convert.ToDecimal(TextBoxAmountNew.Text);
                    //    dtMemoBuffer.Rows[k]["cost"] = Convert.ToDecimal(TextBoxAmountNew.Text)/weight;
                    //}
                    found = 1;
                }
        }

        // find the corresponding account of this stock from stock table
        DataSet ds = new DataSet();
        Common.Getdata(ds, "select acctype,acccode from stock where itype=" + Common.stkTypeValue + " and icode=" + Common.stkCodeValue, "acc");
        if (ds.Tables["acc"].Rows[0]["acccode"] != DBNull.Value)
        {
            Common.stkAccCode = Convert.ToInt32(ds.Tables["acc"].Rows[0]["acccode"]);
            Common.stkAccType = Convert.ToInt32(ds.Tables["acc"].Rows[0]["acctype"]);
        }
        else
        {
            Common.stkAccCode = 0;
            Common.stkAccType = 0;
        }

        if (found == 0)
        {
            if (!(string.IsNullOrEmpty(TextBoxqty.Text)))
            {
                pcs = Convert.ToDecimal(TextBoxqty.Text);
                weight = 0;
                total_cost = Convert.ToDecimal(TextBoxAmount.Text);
                unit_cost = total_cost / pcs;

            }
            if (!(string.IsNullOrEmpty(TextBoxton.Text)))
            {
                pcs = 0;
                weight = Convert.ToDecimal(TextBoxton.Text);
                total_cost = Convert.ToDecimal(TextBoxAmount.Text);
                unit_cost = total_cost / weight;
            }

            //TextBoxAmount.Text = Common.GetItemPrice(Common.stkTypeValue, Common.stkCodeValue).ToString();
            dtMemoBuffer.Rows.Add(Common.stkTypeValue, Common.stkCodeValue, "", Common.stkTypeName, Common.stkCodeName, pcs, unit_cost, total_cost, Common.stkAccType, Common.stkAccCode, "", "", weight);
            //dtMemoBuffer.Columns.Add("itype", lumns.Add("icode", tydd("descript", m"itypestring", tdd("inamestring",("qty", "cost", dd("rowtotal",d("acctype", olumns.Add("acccode",("acctypename","accname","ton", typeof(float));
        }

        GridView3.DataSource = null;
        GridView3.DataSource = dtMemoBuffer;
        GridView3.DataBind();

        
    }
    protected void GridView2_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        if (GridView2.SelectedIndex > -1)
        {
            DataTable dtAccBuffer = new DataTable();
            dtAccBuffer = (DataTable)Session["Raw Account Entry"];


            int i = GridView2.SelectedIndex;

            dtAccBuffer.Rows.RemoveAt(i);
            dtAccBuffer.AcceptChanges();

            GridView2.DataSource = null;
            GridView2.DataSource = dtAccBuffer;
            GridView2.DataBind();

            GridView2.SelectedIndex = -1;

            if (Session["Raw Account Entry"] != null)
            {
                Session.Remove("Raw Account Entry");
            }
            Session.Add("Raw Account Entry", dtAccBuffer);

        }
    }
    protected void Button_Summary_Click(object sender, EventArgs e)
    {
        DataTable dtAccBuffer = new DataTable();
        dtAccBuffer = (DataTable)Session["Raw Account Entry"];
        decimal total_credit = 0;
        foreach (DataRow arow in dtAccBuffer.Rows)
        {
            total_credit = total_credit + Convert.ToDecimal(arow["amount"]);
        }

        DataTable dtMemoBuffer = new DataTable();
        dtMemoBuffer = (DataTable)Session["Raw Entry"];

        DataTable dtBriefMemoBuffer = dtMemoBuffer.Clone();

        //string filterExp = "qty > 0 || ton > 0";
        string filterExp = "";
        DataRow[] drarray;
        drarray = dtMemoBuffer.Select(filterExp);
        decimal total_ton = 0;
        decimal total_debit = 0;
        foreach (DataRow row in drarray)
        {
            dtBriefMemoBuffer.ImportRow(row);
            if (Convert.ToInt32(row["acctype"]) == 0 || Convert.ToInt32(row["acccode"]) == 0)  // means no account mentioned for this stock
            {
                Label1.Text = "error 742 : Debit account not mentioned";
                return;
            }
            total_ton = total_ton + Convert.ToDecimal(row["ton"]);
            total_debit = total_debit + Convert.ToDecimal(row["rowtotal"]);
        }
        TextBox_totalcredit.Text = total_credit.ToString();
        TextBox_totaldebit.Text = total_debit.ToString();
        TextBox_itemtotal.Text = total_ton.ToString()+" Ton";

    
    }
}
